<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2025-01-08 09:19:08
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-03-08 17:10:46
 * @FilePath: \web-appc:\Users\wuheng\Desktop\Wugangrestaurant\hbzc-groupmeal-restaurant-web\src\restaurantViews\purchasing\purchaseorder\components\edit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->

<template>
  <div class="editchaseorde">
    <pb-drawer v-model="isVisible" :title="editData.status == 'updata' ? '编辑订货方案' : '查看订货方案'" :direction="'btt'"
      :size="'92%'" @cancelFn="CancelFn" @confirmFn="confirmFn">
      <searchCard @onSearch="searchFn" :Resetshow="false" class="p-t6" @onReset="resetFn"
        v-show="editData.status !== 'updata'">
        <el-form :model="edtiFrom" label-width="auto" inline @keyup.enter="searchFn">
          <el-form-item label="SKU名称：">
            <pb-input v-model="edtiFrom.skuName" placeholder="请输入SKU名称"></pb-input>
          </el-form-item>
          <el-form-item label="外部编码：">
            <pb-input v-model="edtiFrom.externalCode" placeholder="请输入外部编码"></pb-input>
          </el-form-item>
        </el-form>
      </searchCard>
      <!-- <div class="m-t6 m-b6">
        <pb-input v-model="edtiFrom.combineCondition" placeholder="请商品名称、编码、助记码" @blur="getDetailDataFn" />
      </div> -->
      <pb-table rowKey="dishCode" :indexshow="false" :column="editColumn" style="border-radius: 4px"
        :bottomElement="['pb-page']" :tableData="edittableData" height="580px" :loading="loading"
        :class="{ 'p-t5': editData.status == 'updata' }">
        <template #index="scope">
          <div class="indexBox">
            <div class="flex" :class="{ indexItem: editData.status == 'updata' }">
              <span>{{ scope.$index + 1 }}</span>
            </div>

            <div class="operate" v-if="editData.status == 'updata'">
              <div class="flex">
                <div class="mr-3" @click="addDish">
                  <pb-icon name="add" size="16" class="close-icon"></pb-icon>
                </div>
                <div @click="deleteDish(scope.$index)">
                  <pb-icon name="cut" size="16" class="close-icon"></pb-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template #skuName="scope">
          <div class="flex items-center">
            <el-form-item style="margin: 0;">
              <searchDish @changeExcel="(item: any) => changeExcelFn(item, scope.$index)" :excelDta="scope.row"
                :status="editData.status">
              </searchDish>
            </el-form-item>
          </div>
        </template>
        <template #smallOrderQuantity="{ row }">
          <div>
            <span v-if="editData.status == 'updata'">
              <pb-input v-model="row.smallOrderQuantity" width="100px" type="number" @input="smallinputFn(row)" />

            </span>
            <span v-else>
              {{ row.smallOrderQuantity }}
            </span>
          </div>
        </template>
        <template #maxOrderQuantity="{ row }">
          <div>
            <span v-if="editData.status == 'updata'">
              <pb-input v-model="row.maxOrderQuantity" width="100px" type="number"
                @input="maxOrderinputFn(row)" /></span>
            <span v-else>{{ row.maxOrderQuantity }}</span>
          </div>
        </template>
        <template #orderQuantization="{ row }">
          <div>
            <span v-if="editData.status == 'updata'">
              <pb-input v-model="row.orderQuantization" width="100px" type="number"
                @input="orderQuantizationinputFn(row)" /></span>
            <span v-else>{{ row.orderQuantization }}</span>
          </div>
        </template>
        <template #operate="scope">
          <!-- <PopconfirmButton @confirm="DeleteOrderDetailsFn(row)"></PopconfirmButton> -->
          <pb-button text size="small" @click="deleteDish(scope.$index)">删除</pb-button>
        </template>
      </pb-table>
    </pb-drawer>
  </div>
</template>
<script setup lang="ts">
import { getOrderPlanDetailApi, SaveOrderPlanApi } from '@/api/Purchasing'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import searchDish from './searchexcel.vue'
const emits = defineEmits(['GetOrderListFn'])
const searchFn = () => {
  getDetailDataFn()
}
const resetFn = () => {
  edtiFrom.externalCode = ''
  edtiFrom.skuName = ''
  getDetailDataFn()
}
const isVisible = ref(false)
const loading = ref(false)
const orderQuantizationinputFn = (item) => {
  let value = item.orderQuantization;
  // 去除非数字和小数点的字符
  value = value.replace(/[^\d.]/g, '');
  // 处理多个小数点，只保留第一个
  const dotIndex = value.indexOf('.');
  if (dotIndex !== -1) {
    value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '');
  }
  // 按小数点分割整数和小数部分
  const parts = value.split('.');
  let integerPart = parts[0];
  let decimalPart = parts[1] || '';
  // 限制整数部分最多 6 位
  integerPart = integerPart.slice(0, 6);
  // 限制小数部分最多 2 位
  decimalPart = decimalPart.slice(0, 2);
  // 重新组合
  if (decimalPart) {
    item.orderQuantization = `${integerPart}.${decimalPart}`;
  } else {
    item.orderQuantization = integerPart;
  }
}
const maxOrderinputFn = (item) => {
  let value = item.maxOrderQuantity;
  // 去除非数字和小数点的字符
  value = value.replace(/[^\d.]/g, '');
  // 处理多个小数点，只保留第一个
  const dotIndex = value.indexOf('.');
  if (dotIndex !== -1) {
    value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '');
  }
  // 按小数点分割整数和小数部分
  const parts = value.split('.');
  let integerPart = parts[0];
  let decimalPart = parts[1] || '';
  // 限制整数部分最多 6 位
  integerPart = integerPart.slice(0, 6);
  // 限制小数部分最多 2 位
  decimalPart = decimalPart.slice(0, 2);
  // 重新组合
  if (decimalPart) {
    item.maxOrderQuantity = `${integerPart}.${decimalPart}`;
  } else {
    item.maxOrderQuantity = integerPart;
  }
}
const smallinputFn = (item) => {
  let value = item.smallOrderQuantity;
  // 去除非数字和小数点的字符
  value = value.replace(/[^\d.]/g, '');
  // 处理多个小数点，只保留第一个
  const dotIndex = value.indexOf('.');
  if (dotIndex !== -1) {
    value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '');
  }
  // 按小数点分割整数和小数部分
  const parts = value.split('.');
  let integerPart = parts[0];
  let decimalPart = parts[1] || '';
  // 限制整数部分最多 6 位
  integerPart = integerPart.slice(0, 6);
  // 限制小数部分最多 2 位
  decimalPart = decimalPart.slice(0, 2);
  // 重新组合
  if (decimalPart) {
    item.smallOrderQuantity = `${integerPart}.${decimalPart}`;
  } else {
    item.smallOrderQuantity = integerPart;
  }
};
const changeExcelFn = (item: any, index: any) => {
  // console.log(item, index, '231')
  let falge = false;
  edittableData.value.map(ele => {
    if (ele.skuCode == item.skuCode) {
      falge = true
    }
  })
  if (falge) return createMessage({
    message: `请不要选择重复商品`,
    type: 'error'
  });
  edittableData.value[index].skuName = item.skuName
  Object.assign(edittableData.value[index], item)
  // excelData.value[index].
  // setamountFn(edittableData.value[index])
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const deleteDish = (index) => {
  if (edittableData.value.length == 1) {
    clearObjKey(edittableData.value[0])
  } else {
    edittableData.value.splice(index, 1)
  }
}
let numexcel: any = 0
const addDish = () => {
  if (edittableData.value[0].skuName) {
    numexcel++
    edittableData.value.unshift(JSON.parse(JSON.stringify({ skuCode: null })))
  }
}
const editData = reactive({
} as any)
const edittableData = ref([] as any)
const editColumn = ref([] as any)
const confirmFn = () => {
  let hasInvalidSku = false;
  if (editData.status == 'updata') {
    for (let index = 0; index < edittableData.value.length; index++) {
      const el = edittableData.value[index];
      // console.log(el, '222');
      if (el.skuName === '' || !el.skuName) {
        createMessage({
          message: `第${index + 1}行请选择商品`,
          type: 'error'
        });
        hasInvalidSku = true
        break; // 跳出循环
      }
    }
    if (hasInvalidSku) return
    SaveOrderPlanApi({
      orderPlanId: editData.orderPlanId,
      orderPlanDetailsSaveReqList: edittableData.value,
    }).then(res => {
      if (res.code == 2000) {
        createMessage({
          message: '编辑成功'
        })
        emits('GetOrderListFn')
        isVisible.value = false
      }
    })
  } else {
    emits('GetOrderListFn')
  }
  // console.log(edittableData.value, '2')
}
const CancelFn = () => {
  isVisible.value = false
}
const edtiFrom = reactive({
  "skuName": "",
  "externalCode": ""
})
const getDetailDataFn = () => {
  loading.value = true
  getOrderPlanDetailApi({
    pageSize: -1,
    orderPlanId: editData.orderPlanId,
    ...edtiFrom
  }).then(res => {
    loading.value = false
    edittableData.value = res.data.records ? res.data.records.length == 0 ? editData.status == 'updata' ? [{}] : [] : res.data.records : res.data.records
  })
}
const show = (row: any) => {
  // console.log(editData, row)
  Object.assign(editData, row)
  if (row.status == 'updata') {
    editColumn.value = [
      {
        slot: "index",
        width: 60,
        name: "序号 ",
        align: 'center'
      },
      {
        slot: "skuName",
        name: "商品名称",
      },
      {
        key: 'externalCode',
        name: '外部编码'
      },
      {
        key: 'accountingUnitName',
        name: "计量单位",
      },
      {
        key: 'specifications',
        name: "规格",
      },
      {
        slot: "smallOrderQuantity",
        name: "最小订货数量",
        align: 'right'
      },
      {
        slot: "maxOrderQuantity",
        name: "最大订货数量",
        align: 'right'
      },
      {
        slot: 'orderQuantization',
        name: '订货取整',
        align: 'right'
      },
      {
        key: 'requiredOrder',
        name: '必定'
      },
      {
        key: "orderCycle",
        name: "订货周期",
      },
      {
        width: 180,
        slot: "operate",
        name: "操作",
        fixed: 'right',
      },
    ]
  } else {
    editColumn.value = [
      {
        slot: "index",
        width: 60,
        name: "序号 ",
        align: 'center'
      },
      {
        slot: "skuName",
        name: "商品名称",
      },
      {
        key: 'externalCode',
        name: '外部编码'
      },
      {
        key: 'accountingUnitName',
        name: "计量单位",
      },
      {
        key: 'specifications',
        name: "规格",
      },
      {
        slot: "smallOrderQuantity",
        name: "最小订货数量",
        align: 'right'
      },
      {
        slot: "maxOrderQuantity",
        name: "最大订货数量",
        align: 'right'
      },
      {
        slot: 'orderQuantization',
        name: '订货取整',
        align: 'right'
      },
      {
        key: 'requiredOrder',
        name: '必定'
      },
      {
        key: "orderCycle",
        name: "订货周期",
      },
    ]
  }
  getDetailDataFn()
  isVisible.value = true
}
defineExpose({
  show
})
</script>
<style lang="scss" scoped>
.editchaseorde {
  .top {
    padding-top: 24px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
    align-items: center;

    >div:nth-child(2n) {
      line-height: 22px;
      min-width: 102px;
      font-weight: 500;
      font-size: 14px;
      color: rgba(0, 0, 0, 0.85);
      margin-right: 20px;
    }

    .colorgreen {
      font-family: DIN, DIN;
      font-weight: 500;
      font-size: 16px;
      color: #0D968B;
      line-height: 24px;
    }

    .smallspan {
      font-weight: 400;
      font-size: 12px;
      color: rgba(0, 0, 0, 0.45);
    }
  }
}

.footerBtn {
  display: flex;
  justify-content: flex-end;
}

.indexBox {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  cursor: pointer;

  .indexItem {
    align-items: center;
  }

  .operate {
    display: none;
  }
}

.indexBox:hover {
  .indexItem {
    display: none;
  }

  .operate {
    display: block;
  }
}
</style>
